package algorithm.leetcode.array;

import java.util.ArrayList;
import java.util.List;

/**
 * 螺旋输出数组
 */
public class SpiralOrder {

    public List<Integer> spiralOrder(int[][] matrix) {
        int left = 0;
        int right = matrix[0].length -1;
        int top = 0;
        int bottom = matrix.length -1;

        int total = matrix.length * matrix[0].length;

        int count = 0;
        List<Integer> list = new ArrayList();

        while (count < total) {
            //从左到右
            for(int index = left; index <= right; index++) {
                list.add(matrix[top][index]);
                count++;
            }
            top ++;
            if(count>=total){
                break;
            }

            //从上到下
            for(int index = top; index <= bottom; index++) {
                list.add(matrix[index][right]);
                count++;
            }
            right --;
            if(count>=total){
                break;
            }

            //从右到左
            for(int index = right; index >= left; index--) {
                list.add(matrix[bottom][index]);
                count++;
            }
            bottom --;
            if(count>=total){
                break;
            }

            //从下到上
            for(int index = bottom; index >= top; index--) {
                list.add(matrix[index][left]);
                count++;
            }
            left ++;
            if(count>=total){
                break;
            }
        }
        return list;
    }

    public static void main(String[] args) {
        int[][] arr = new int[][] {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        new SpiralOrder().spiralOrder(arr).stream().forEach(item->{
            System.out.println(item);
        });
    }
}
